package Dao;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnection {

    // 数据库URL, 用户名, 密码
    private static final String URL = "jdbc:mysql://localhost:3306/weatherinfo";
    private static final String USER = "root";
    private static final String PASSWORD = "root";

    // 单例模式，确保只有一个数据库连接实例
    private static Connection connection;

    // 私有构造函数，防止外部实例化
    private DatabaseConnection() {}

    /**
     * 获取数据库连接
     * @return 数据库连接对象
     * @throws SQLException 如果连接失败
     */
    public static Connection getConnection() throws SQLException {
        if (connection == null || connection.isClosed()) {
            connection = DriverManager.getConnection(URL, USER, PASSWORD);
        }
        return connection;
    }

    /**
     * 关闭数据库连接
     */
    public static void closeConnection() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try {
            // 获取数据库连接
            Connection conn = getConnection();
            System.out.println("1.数据库连接成功");

            // 在这里执行数据库操作

            // 关闭数据库连接
            closeConnection();
            System.out.println("数据库连接已关闭");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
